//
//  Element.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-5.
//  Copyright 2009 xhzhang. All rights reserved.
//

#import "Element.h"


@implementation Element

/**
 * 快捷方式，指定名称创建元素
 */
+ (id)elementWithName:(NSString *)eName{
	return [[[Element alloc] initWithName:eName] autorelease];
}

/**
 * 初始化元素
 */
- (id)initWithName:(NSString *)eName{
	if(self = [super init]){
		elementName = [eName copy];
	}
	return self;
}

/**
 * 获取节点名称
 */
- (NSString *)getNodeName{
	return elementName;
}

- (NSInteger)nodeType{
	return ELEMENT_NODE;
}

/**
 * 通过名称来获取元素
 * 取当前文档中的，所有以 ename命名的一级子元素
 */
-(NSArray *)getElementsByName:(NSString *)ename{
	NSMutableArray *ret = nil;
	int cnum = [childs count];
	if(cnum > 0){
		// TODO 查找以ename命名的子元素
		Node *node = nil;
		NSString *nname = nil;
		ret = [[[NSMutableArray alloc] init] autorelease];
		for (int i = 0; i < cnum; i++) {
			node = (Node *)([childs objectAtIndex:i]);
			nname = [node getNodeName];
			if([nname isEqualToString:ename]){
				[ret addObject:node];
			}
		}
	}
	return ret;
}

- (NSString *)toXML{
	NSMutableString *ret = [NSMutableString string];
	[ret appendFormat:@"<%@",elementName];
	if(attributes){
		NSArray *keys = [attributes allKeys];
		int len = [keys count];
		NSString *key;
		NSString *value;
		for(int i = 0;i<len;i++){
			key = (NSString *)[keys objectAtIndex:i];
			value = (NSString *)[attributes objectForKey:key];
			[ret appendFormat:@" %@=\"%@\"",key,value];
		}
	}
	
	if([self hasChild]){
		NSArray *chds = [self getChildNodes];
		[ret appendString:@">"];
		Node *node;
		int len = [chds count];
		for(int i = 0;i<len;i++){
			node = (Node *)[chds objectAtIndex:i];
			[ret appendString:[node toXML]];
		}
		[ret appendFormat:@"</%@>",elementName];
	}else{
		[ret appendString:@" />"];
	}
	return ret;
}


- (void)dealloc{
	[elementName release];
	[super dealloc];
}

@end
